package com.atguigu.daijia.driver.service.impl;

import com.atguigu.daijia.common.constant.RedisConstant;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.Result;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.driver.client.DriverInfoFeignClient;
import com.atguigu.daijia.driver.service.DriverService;
import com.atguigu.daijia.model.vo.driver.DriverLoginVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class DriverServiceImpl implements DriverService {

    @Resource
    private DriverInfoFeignClient driverInfoFeignClient;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public String login(String code) {
        // 远程调用获取用户信息
        Result<Long> login = driverInfoFeignClient.login(code);
        if (login.getCode().equals(ResultCodeEnum.FAIL.getCode())) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        Long driverId = login.getData();

        // 生成UUID token 字符串
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        // 存入redis里
        redisTemplate.opsForValue().set(
                RedisConstant.USER_LOGIN_KEY_PREFIX + token,
                driverId.toString(),
                RedisConstant.USER_LOGIN_KEY_TIMEOUT,
                TimeUnit.SECONDS
        );
        return token;
    }

    /**
     * 获取司机登录信息
     * @param userId
     * @return
     */
    @Override
    public DriverLoginVo getDriverLoginInfo(Long userId) {
        Result<DriverLoginVo> driverLoginInfo = driverInfoFeignClient.getDriverLoginInfo(userId);
        if (driverLoginInfo.getCode().equals(ResultCodeEnum.FAIL.getCode())) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        return driverLoginInfo.getData();
    }
}
